【问题标题】:Determine type from non-type template parameter从非类型模板参数确定类型
【发布时间】:2017-01-11 19:32:04
【问题描述】:

我希望我能做到:

template <typename T x>
struct Test {
    T val{x};
};

int main() {
    Test<3> test;
    return test.val;
}

But I can't. Right?


我正在回答一个问题here,我使用以下模板:

template <typename T, typename V, typename VP, V(T::*getf)(), void (T::*setf)(VP)>

每种类型都是手动指定的。但这是重复的,因为 TVVP 已经包含在指向成员函数 getfsetf 的类型的指针中。


但如果我尝试使用仅包含的模板

template <V(T::*getf)(), void (T::*setf)(VP)>

template <V(T::*getf)(), void (T::*setf)(VP), typename T, typename V, typename VP>

那么无法确定类型。


接下来我尝试了专业化:

template <typename T, typename T2>
struct Accessor;

template <typename V, typename T, typename VP>
struct Accessor <V(T::*)(), void (T::*)(VP)>

如果使用,它将确定所有类型

typedef Accessor<
    decltype(&TargetClass::GetFoo), 
    decltype(&TargetClass::SetFoo)> fooAcessor;

但是现在我没有指针了,只有类型。


有没有办法编写模板,以便可以根据非类型模板参数自动确定类型?

【问题讨论】:

    标签: c++ templates member-function-pointers


    【解决方案1】:

    有没有办法编写模板,以便可以根据非类型模板参数自动确定类型?

    在 C++17 中,是的,感谢declaring non-type template parameters with auto

    template <auto x>
    struct Test {
        decltype(x) val{x};
    };
    

    在 C++17 之前,没有。你必须写:

    template <class T, T x>
    struct Test {
        T val{x};
    };
    

    【讨论】:

    • @Quentin Ahem, Westie!
    • 哎呀。 Busted cover is busted, I don't know a thing about dogs :( -- 但是,嘿,有魔法,还有 C++,它是一条狗,这就像只有 25% 的失败!
    猜你喜欢
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多