decltype比较

Tom*_*Tom 5 c++ templates decltype c++11

有没有办法比较decltypeC++ 11 的结果?

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

// 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)>();
}
Run Code Online (Sandbox Code Playgroud)

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

class AFreeFunction {
public:
    operator bool() { return false; }
};
Run Code Online (Sandbox Code Playgroud)

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

Xeo*_*Xeo 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
Run Code Online (Sandbox Code Playgroud)

如果两个参数f属于同一类型,则#1比#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
}
Run Code Online (Sandbox Code Playgroud)

std::is_same将来自std::true_type两种类型是否相同,std::false_type如果不相同.


Meh*_*dad 5

为什么无效?a的结果decltype是一种类型.所以它说的是这样的

if (int == int)
Run Code Online (Sandbox Code Playgroud)

语言显然不允许.

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

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