c++ - 检查方法是否为常量

标签 c++ function templates constants typetraits

有人知道如何检查任意方法是否为常量?

喜欢:

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/

相关文章:

c++ - NetFlow v5 - 导出流记录缺失字段

html - 是我的 HTML "leaking",因为它显示异常行为

c++ - 为特定的模板方法实例定义别名

c++ - 为什么编译不会失败?

c++ - 如何在 C++ 中为 Windows 7 x64 的特定文件提取 "Date column"值

python - 如何通过单击 PyQt 中的按钮将参数传递给函数?

c++ - 调用这个函数(没有定义)是如何工作的?

c - C中的二叉树崩溃

基于 C++ 模板参数的编译

c++ - 为什么 C++ lambda 在多次调用时比普通函数慢?