标签: template-meta-programming

C++ 是否可以在编译时识别对象的数据类型?

可以使用 RTTI 在运行时识别数据类型,但是我们如何在编译时做到这一点,这可能吗?

c++ templates template-specialization template-meta-programming

0
推荐指数
1
解决办法
188
查看次数

模板元编程为此?

struct findCategoryByName
{
    string name;

    bool operator()(const category& a)
    {
        return (a.name == name);
    }
};

struct findEntryByName
{
    string name;

    bool operator()(const entry* a)
    {
        return (a->name == name);
    }
};
Run Code Online (Sandbox Code Playgroud)

有没有办法使用模板元编程或其他东西?如果有帮助,我总是可以使用指针使其成为类别*.

c++ template-meta-programming

-1
推荐指数
1
解决办法
257
查看次数

有没有办法在C++中为模板化函数赋予动态值?

模板元编程的"hello,world"可以被认为是阶乘代码:

template <unsigned int n>
struct factorial {
    enum { value = n * factorial<n - 1>::value };
};

template <>
struct factorial<0> {
    enum { value = 1 };
};
Run Code Online (Sandbox Code Playgroud)

所以我们可以通过这样做得到阶乘

cout << factorial<4>::value << endl; //It will print 24
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

int N = 4;
cout << factorial<N>::value << endl; //COMPILE ERROR
Run Code Online (Sandbox Code Playgroud)

有没有办法在C++中为模板化函数提供动态值?

c++ templates metaprogramming template-meta-programming

-1
推荐指数
1
解决办法
177
查看次数

SFINAE 方法存在性检查 - 带/不带参数

下面的代码似乎是一种不错的 SFINAE 方法来检查没有参数的方法是否存在:

template<typename T> struct has_size_method {
private:
    typedef std::true_type yes;
    typedef std::false_type no;
    template<typename U> static auto test(int) 
        -> decltype(std::declval<U>().size() == 1, yes());
    template<typename> static no test(...);
public:
    static constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value;
};
Run Code Online (Sandbox Code Playgroud)

(从这里解除)。我如何适应它以获取参数?下列

template<typename T, typename Key> struct has_find_method {
private:
    typedef std::true_type yes;
    typedef std::false_type no;
    template<typename U> static auto test(int)
        -> decltype(std::declval<U>().find(std::declval<const Key&>()) == 1, yes());
    template<typename> static no test(...);
public:
    static constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value;
};
Run Code Online (Sandbox Code Playgroud)

不起作用,尽管它可以编译(GodBolt)。我究竟做错了什么?

注意:虽然这个问题有其自身的优点(我相信),但它也是一个 …

c++ sfinae template-meta-programming c++11

-1
推荐指数
1
解决办法
50
查看次数