泛型操作符T()的enable_if

enable_if for generic operator T()

本文关键字:enable if 操作符 泛型      更新时间:2023-10-16

程序示例:

#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) )
其中switch_type trait可以被扩展以解决特定应用相关类型(属性类型)的歧义。