如何以不同的方式专门化 typedef 及其隐式类型?
我有这样的事情:
typedef int AnotherType;
template <typename T> Func( T Value );
// And I want to specialize these two cases separately:
template <> bool Func<int>( int Value ) {...}
template <> bool Func<AnotherType>( AnotherType Value ) {...}
我真的不需要专门针对 int,我真正需要的是为 AnotherType 执行不同的函数。我无法更改 AnotherType 或基本函数的定义。
由于 SFINAE,重载也无济于事。
I have something like this:
typedef int AnotherType;
template <typename T> Func( T Value );
// And I want to specialize these two cases separately:
template <> bool Func<int>( int Value ) {...}
template <> bool Func<AnotherType>( AnotherType Value ) {...}
I don't really need to specialize for int, what I really need is to execute a different function for AnotherType. And I cannot change the definition of AnotherType or the base function.
Overloading doesn't help either because of SFINAE.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
答案是否定的。当您 typedef 时,您为类型创建了别名,而不是其本身的实际类型。编译器会将两者视为相同。这就是为什么:
会编译。他们都是整数。
The answer is no. When you typedef you create an alias for a type, not an actual type in and of itself. The compiler will treat both the same. That's why:
Will compile. They're both ints.
您可以使用BOOST_STRONG_TYPEDEF。
You could use BOOST_STRONG_TYPEDEF.
我很确定你不能让编译器以不同的方式对待 int 和 AnotherType 。 typedef 所做的只是别名类型——它实际上并不创建新类型;而是创建新类型。根据 typedef 构造的定义,编译器在所有情况下都会同等对待 int 和 AnotherType。
如果您需要一个仅包含 int 且以不同方式处理的类型,您可能应该只创建一个单成员
struct
。对包含的 int 进行的大多数操作将编译为与裸 int 相同的机器代码,但现在您的数据类型可以拥有自己的模板专业化等。I'm pretty sure you can't have the compiler treat int and AnotherType differently. All typedef does is alias types -- it doesn't actually create a new type; by definition of the typedef construct, the compiler will treat int and AnotherType equivalenty in all cases.
If you need to have a type with just an int that IS treated differently, you should probably just make a single-member
struct
. Most operations on the contained int will compile to the same machine code as a bare int, but now your data type can have its own template specializations and such.而且我无法更改 AnotherType 或基本函数的定义。
那么你就完蛋了。对不起。如果您无法更改定义以使用强 typedef,那么您真正拥有的唯一选项(强 typedef)就不是一个选项。
And I cannot change the definition of AnotherType or the base function.
Then you're screwed. Sorry. The only option you really have, a strong typedef, is not an option if you can't change the definition to use a strong typedef.
编译器会将这两种特化视为完全相同,因为
AnotherType
只是int
的另一个名称。您说您不需要专门化int
,因此只需完全删除该专门化并让它专门化AnotherType
恰好适用的任何类型。The compiler will treat both of the specializations as exactly the same, since
AnotherType
is just another name forint
. You say you don't need to specialize forint
, so just remove that specialization completely and let it specialize on whatever typeAnotherType
happens to work out to.