decltype比较

时间:2012-08-08 09:33:03

标签: c++ templates c++11 decltype

有没有办法比较C ++ 11中decltype的结果?

换句话说,为什么这段代码无效:

template<typename T, typename U>
void func(T& t, U& u) {
    if(decltype(t) == decltype(u)) {
        // Some optimised version for this case
    } else {
        // A more general case for differing types
    }
}

我知道在某些情况下,这个特殊问题可以通过部分模板专业化来解决;我的问题是关于decltype的比较。

编辑:在尝试通过SFINAE提供免费功能默认设置的过程中出现了这个问题。或许更好的问题是为什么这是无效的:

template<bool B>
bool SomeFunction() { ... }

template<typename T, typename U>
bool SomeFunctionWrapper(T& t, U& u) {
    SomeFunction<decltype(t) == decltype(u)>();
}

我已经找到了另一个解决方案(根本不涉及模板),但在一个阶段我尝试了这个:

// If it exists, the free function is defined as
// bool AFreeFunction();
typedef struct { char } undefined;
template<typename T = void>
undefined AFreeFunction();

template<bool B>
bool AFreeFunctionWrapper_() {
    return false;
}

template<>
bool AFreeFunctionWrapper_<false>() {
    return AFreeFunction();
}

bool AFreeFunctionWrapper() {
    return AFreeFunctionWrapper_<decltype(AFreeFunction()) == decltype(undefined)>();
}

我最终使用GCC 4.6获得了此策略的变体,但随后发现MSVC中的模板函数不允许使用默认模板参数,即使在2012 RC中也是如此。所以最终的解决方案看起来像这样:

class AFreeFunction {
public:
    operator bool() { return false; }
};

如果定义了该函数,则会调用它。如果不是,则将其解释为类的构造函数,然后将其隐式转换为bool

3 个答案:

答案 0 :(得分:8)

您通常通过标记调度来解决此问题。此外,您已经分别拥有tu - T&U&的“声明类型”。要比较相等类型,可以使用std::is_same。但是,重载解析已经为您解决了这个问题:

template<class T>
void f(T& v1, T& v2){ ... } // #1

template<class T, class U>
void f(T& t, U& u){ ... } // #2
如果f的两个参数属于同一类型,则#p>#2比#2更专业。如果你出于某种原因坚持通过手动类型比较来解决这个问题,那么它应该如何应用前面提到的要点:

#include <type_traits>

namespace detail{
template<class T, class U>
void f(T& t, U& u, std::true_type){ ... } // #1

template<class T, class U>
void f(T& t, U& u, std::false_type){ ... } // #2
} // detail::

template<class T, class U>
void f(T& t, U& u){
  detail::f(t, u, std::is_same<T,U>()); // tag dispatching
}
如果两种类型相同,

std::is_same将来自std::true_type,如果不相同,则来自std::false_type

答案 1 :(得分:5)

为什么无效? decltype的结果是一种类型。所以它说的是

if (int == int)

语言显然不允许。

您需要将函数的两个部分分开,并将专用部分放在一个专门的类中的函数中,然后将调用转发到那里。这很痛苦。

或者,您可以使用typeid或运行时类型信息,如果您的实现正确实现它,尽管这会将所有内容推迟到程序运行时(这样可以减少优化)。

答案 2 :(得分:3)

您可以使用SFINAE(std::enable_if)执行此操作:

template<typename T, typename U>
typename std::enable_if<std::is_same<T, U>::value, void>::type func(T& t, U& u) {
    std::cout << "same\n";
}
template<typename T, typename U>
typename std::enable_if<!std::is_same<T, U>::value, void>::type func(T& t, U& u) {
    std::cout << "different\n";
}

正如Mehrdad所说,decltype(t)decltype(u)分别是类型(T &U &),而不是值,因此无法在值表达级别进行比较,但必须是在元表达(模板)级别进行比较。