最小的例子:
template <typename TFunc>
void func(TFunc f)
{
//D do something like:
double x{1}, y{2}。
bool z = f(x) < f(y); //在某處做比較。
}
我想給該函式添加一個static_assert,以檢查f(x)是否回傳一個std::less計算的型別。換句話說,我希望f(x) < f(y)能夠被編譯。我目前正在做這樣的事情:
static_assert((decltype(f(0)){} < decltype(f(0)){}) == false, "函式f必須回傳一個弱有序型別。 ")。)
但是在這里我假設函式回傳的是一個可以被默認初始化的型別。是否有更好的方法來檢查這個問題?
uj5u.com熱心網友回復:
更復雜的代碼,但這似乎是更普遍的檢查方法,以防有人需要這樣做:
。
template <typename T>
class is_weakly_ordered_type
{
private:
typedef int yes[1] 。
typedef int no[2] 。
template <typename S>
static yes& test(decltype(std: :declval<S>() < std::declval<S>())){}。
template <typename S>
static no& test(...){}。
public:
static const bool value = sizeof(test< T>(nullptr)) == sizeof(yes)。
};
template <typename TFunc, typename ...。TArgs>
class returns_weakly_ordered_type
{
private:
using TFuncRef = TFunc& 。
using return_type = typename std::result_of<TFuncRef(TArgs...)> :type。
public:
static const bool value = is_weakly_ordered_type< return_type> ::value;
};
現在你可以做到
template <typename TFunc>
void func(TFunc f)
{
static_assert(returns_weakly_ordered_type<decltype(func), double>:value, "函式func應該回傳一個弱有序型別。 ")。)
//做一些類似于:的事情。
double x{1}, y{2}。
bool z = f(x) < f(y); //在某處做比較。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314172.html
標籤:
上一篇:C 中的類模板和友誼
