有人知道如何检查任意方法是否为常量?
喜欢:
static_assert(is_const<vector<int>::size>::value, "size is not const");
static_assert(!is_const<vector<int>::push_back>::value, "push_back is const");
好问题 T.C :) 我发现了该方法的一个特定重载,如果我发现的方法是非常量,我只想设置一个修改后的标志。
这是我的模板和 maroes:
#define FRET_DECL_TYPE(Function) \
template<typename T_, typename ... Args_> \
struct f_ret##Function { typedef decltype(std::declval<T_&>().Function(std::declval<Args_&&>()...)) type; };
#define RPROP_PROXY_METHOD(Function) \
FRET_DECL_TYPE(Function) \
template<typename ... Args> \
typename f_ret##Function<T, Args...>::type \
Function(Args&& ... args) const { return this->GetReference().Function(static_cast<Args&&>(args)...); }; \
template<typename ... Args> \
typename f_ret##Function<T, Args...>::type \
Function(Args&& ... args) { this->SetModified(true); return this->GetReference().Function(static_cast<Args&&>(args)...); }; \
最佳答案
可以使用 “Walter Brown's void_t
trick” 来完成尽管如果您需要为很多成员使用它,它很快就会变得有点冗长。您可以考虑使用宏来避免为每个成员一次又一次地重复模板定义。
#include <iomanip>
#include <iostream>
#include <type_traits>
#include <vector>
template<typename>
struct void_t
{
using type = void;
};
template<class C, typename = void>
struct has_const_size : std::false_type {};
template<class C>
struct has_const_size<C, typename void_t<decltype(std::declval<const C>().size())>::type> : std::true_type {};
template<class C, typename = void>
struct has_const_clear : std::false_type {};
template<class C>
struct has_const_clear<C, typename void_t<decltype(std::declval<const C>().clear())>::type> : std::true_type {};
int
main()
{
std::cout << "std::vector<int>::size() " << std::boolalpha << has_const_size<std::vector<int>>::value << std::endl;
std::cout << "std::vector<int>::clear() " << std::boolalpha << has_const_clear<std::vector<int>>::value << std::endl;
}
输出:
std::vector<int>::size() true
std::vector<int>::clear() false
关于c++ - 检查方法是否为常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544579/