c 类构造函数模板,带有std :: enable_if和std :: decay
c++ class constructor template with std::enable_if and std::decay
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>’
从错误消息中,我看到了可操纵的部分存在问题,因为它不会传递在布尔上,但我不明白为什么。问题在哪里,我应该如何更改代码?也许可以更好地解决此类问题?
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 }
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- Linux gnu++11,在运行时获取"Enable multithreading to use std::thread: Operation not permitted"