Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为通用运算符T()启用_if_C++_Templates_G++_Typetraits - Fatal编程技术网

C++ 为通用运算符T()启用_if

C++ 为通用运算符T()启用_if,c++,templates,g++,typetraits,C++,Templates,G++,Typetraits,下面是一个示例程序: #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*&

下面是一个示例程序:

#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;
}
#包括
#包括
模板
结构测试
{
运算符int()常量{puts(“?”);返回0;}
模板
运算符T()常量{puts(“T”);返回0;}
};
int main()
{
试验t;
char*c=(char*)t;
开关(t)
{
案例0:断裂;
}
返回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*]’
user@user:~$g++-4.7-std=c++0x test.cpp
test.cpp:在函数“int main()”中:
test.cpp:13:14:错误:来自“test”的默认类型转换不明确
test.cpp:13:14:错误:候选转换包括“template test::operator void*()const[with T=T;=;X=void*]”
g++4.6编译它时没有错误,实际上调用了不同的运算符

有没有办法在g++4.7下实现这一点


更新:实际上它在4.6中工作,没有任何启用\u,如果在所有。。。因此,这个问题仍然适用,但我现在不确定enable_if是否有帮助。

如果您在
int
中添加一个显式强制转换:

开关((int)t)

然后它应该编译

我认为它抱怨转换不明确,因为存在多个类型可以保存
0

但我使用的是g++4.8。

我发现至少有一个“可接受”的解决方案:

#define switch(x) \
    switch( (typename switch_type<__typeof(x)>::type)(x) )
#定义开关(x)\
开关((类型名称开关\类型::类型)(x))

可以扩展哪个开关类型特征来解决特定应用程序相关类型(属性类型)的模糊性。

如果默认了的第二个模板参数,则可以直接专门化
测试
,而不是使用
标准::启用。你不需要使用它。嗯,实际上“test”不是一个模板类,而X类型来自宏。。。我认为简化代码以适应如此多的变化。我可能会考虑创建一个模板类,但这可能会带来太多麻烦。为什么需要模板转换运算符?在实际应用中,“测试”类模拟属性。我希望避免更改在Windows下而不是Linux下编译此代码的数千个位置。实际应用程序类“test”具有运算符(例如)void*,这是属性类型,但它被强制转换为例如Object*。或者它有运算符EnumType,但它被强制转换为EnumType2。这就是我试图避免使用所有这些运算符的原因——在代码中更改2000个开关。所以,虽然这会奏效,但这不是我需要的解决方案。我有一种奇怪的感觉,你的雄心壮志可能是运气不好。我认为有一条规则说类型转换需要对定义自己类型的对象进行显式转换……但我可能错了。