C++ compile time check if method exists in template type

你说的曾经没有我的故事 提交于 2021-02-07 14:13:19

问题


I have a template that calls a member function. How do I check with static_assert that the method exists?

struct A {

};

struct B {
    int foo() { return 42; } };

template <typename T> struct D {
    static_assert(/* T has foo */, "T needs foo for reasons");

    int bar() {
       return t.foo();
    }

    T t; };

int main() {
    D<A> d;

    std::cout << d.bar() << std::endl;

    return 0; }

I know this will just generate a compiler error that A does not have foo but I would like to check and give a better error output using static_assert.


回答1:


Since you use static_assert I assert that you are using at least C++11. This allows to write something like this:

#include <type_traits>

template<class ...Ts>
struct voider{
    using type = void;
};

template<class T, class = void>
struct has_foo : std::false_type{};

template<class T>
struct has_foo<T, typename voider<decltype(std::declval<T>().foo())>::type> : std::true_type{};

And you just use static field value (has_foo<your_type>::value) - if it's true then your type has function foo.




回答2:


[Constraint templates][۱] has been a long discussion - ever since 2005 or so - on std forums. But the outcome has yet to wait til C++20.



来源:https://stackoverflow.com/questions/55191505/c-compile-time-check-if-method-exists-in-template-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!