带有std :: enable_if和std :: decay的c ++类构造函数模板

时间:2018-04-03 00:49:58

标签: c++ constructor std enable-if

class DirectoryEntry; // forward declaration

template <class T>
struct isPathable { static const bool value = false; };

template<> struct isPathable<char*>
{
    static const bool value = true;
};
template<> struct isPathable<const char*>
{
    static const bool value = true;
};
template<> struct isPathable<std::string>
{
    static const bool value = true;
};
template<> struct isPathable<std::vector<char> >
{
    static const bool value = true;
};
template<> struct isPathable<std::list<char> >
{
    static const bool value = true;
};
template<> struct isPathable<DirectoryEntry>
{
    static const bool value = true;
};

class path
{
private:
    std::string m_pathname;
public:

    // constructors:
    // ------------------------
    path() noexcept {}
    path(const path &p) : m_pathname(p.m_pathname) {}

    template <class Source>
    path(Source const &source,
        std::enable_if_t<isPathable<std::decay_t<Source>> >* = 0)
    {
        // do stuff
    }
...
};

我收到以下错误消息:

/usr/bin/c++   -I../lib -Wall -Werror -std=c++17 -g   -pthread -MD -MT app/CMakeFiles/infinityApp.dir/src/main.cpp.o -MF app/CMakeFiles/infinityApp.dir/src/main.cpp.o.d -o app/CMakeFiles/infinityApp.dir/src/main.cpp.o -c ../app/src/main.cpp

error: type/value mismatch at argument 1 in template parameter list for ‘template<bool _Cond, class _Tp> using enable_if_t = typename std::enable_if::type’

std::enable_if_t<isPathable<std::decay_t<Source>> >* = 0)
                                                  ^
note:   expected a constant of type ‘bool’, got ‘isPathable<typename std::decay<_Tp>::type>’

从错误消息中我看到isPathable部分存在问题,因为它没有传递bool,但我不明白为什么。问题在哪里?我应该如何更改我的代码?也许对这些问题有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

template<> struct isPathable<char*>
{
    static const bool value = true;
};

你以这种方式定义了一堆专业。您的专业化定义了一个布尔成员value,初始化为true。在你的构造函数中:

/* ... */ std::enable_if_t<isPathable<std::decay_t<Source>> >* = 0)

请注意,std::enable_if_t的模板参数是布尔值,但如果您解析出此处指定的内容,则指定typename作为模板参数。你显然意味着... ...

/* ... */ std::enable_if_t<isPathable<std::decay_t<Source>>::value >* = 0)

您可以尝试改进模板的其他一些调整:

  • 将您的班级成员定义为constexpr,而不仅仅是const

  • 您可以通过执行以下操作来避免对构造函数使用伪形式参数:

    template <class Source,
          std::enable_if_t<isPathable<std::decay_t<Source>>::value >>
    path(Source const &source)
    {
        // do stuff
    }