泛型操作符T()的enable_if
enable_if for generic operator T()
程序示例:
#include <type_traits>
#include <stdio.h>
template <typename X>
struct test
{
operator int() const { puts("?"); return 0; }
template <typename T, typename = typename std::enable_if<std::is_same<X, void*>::value, T>::type>
operator T() const { puts("T"); return 0; }
};
int main()
{
test<void*> t;
char* c = (char*)t;
switch (t)
{
case 0: break;
}
return 0;
}
这是g++-4.7给出的错误
user@user:~$ g++-4.7 -std=c++0x test.cpp
test.cpp: In function ‘int main()’:
test.cpp:13:14: error: ambiguous default typeconversion from ‘test<void*>’
test.cpp:13:14: error: candidate conversions include ‘template<class T, class> test::operator void*() const [with T = T; <template-parameter-2-2> = <template-parameter-1-2>; X = void*]’
g++ 4.6编译时没有错误,实际上调用了不同的操作符。
在g++ 4.7下有办法让这个工作吗?
更新:实际上它在4.6中没有任何enable_if…所以问题仍然适用,但我现在不确定enable_if是否有帮助。
如果您在这里为int
添加显式强制转换:
switch ((int)t)
那么它应该可以编译。
我认为它在抱怨转换是模糊的,因为存在不止一种类型可以保存0
值。
我找到了至少一个"可接受"的解决方案:
#define switch(x)
switch( (typename switch_type<__typeof(x)>::type)(x) )
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- SFINAE with boost enable if