jjzjj

c++ - SFINAE 用于检测非成员模板函数的存在

coder 2024-02-04 原文

TL;DR 我想写一个模板函数 Process(T value)根据非成员函数的存在,对于不同的值表现不同 CreateProcessor<T>() .我能为此做什么?

我对 SFINAE 有疑问。假设我们需要支持函数 CreateProcessor返回接口(interface) IProcessor<T> 的实现对于某些类型 T .

在 C++ 中,我们不能为一个函数创建多个仅在返回类型上不同的重载,因此我们必须创建函数 CreateProcessor也是由 T 参数化的模板函数.

现在假设我们要写一个模板函数Process<T>(T value)根据 CreateProcessor<T>() 的存在而不同,即它应该处理 value在情况下使用处理器 CreateProcessor<T>()已实现,否则会导致错误。

我尝试编写以下代码:

#include <cstdio>
#include <type_traits>

// A workaround for void_t as described here: http://en.cppreference.com/w/cpp/types/void_t.
template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;

// An interface for a processor that receives a value of specific type.
template<class T>
class IProcessor {
public:
    virtual void process(T value) = 0;
};

// A processor for int.
class IntProcessor : public IProcessor<int> {
public:
    virtual void process(int value) override {
        printf("IntProcessor::process is called for value = %d\n", value);
    }
};

// Template prototype.
template<class T> 
IProcessor<T>* CreateProcessor();

// Template specialization for int.
template<>
IProcessor<int>* CreateProcessor() {
    return new IntProcessor();
}

// Detector of CreateProcessor.
template<class, class=void>
struct CreateProcessorImplemented : std::false_type { };

template<class T>
struct CreateProcessorImplemented<T, void_t<decltype(CreateProcessor<T>())>> : std::true_type { };


// Specializations depending on existence of CreateProcessor.
template <typename T>
typename std::enable_if<CreateProcessorImplemented<T>::value, void>::type Process(T value) {
    IProcessor<T>* processor = CreateProcessor<T>();
    processor->process(value);
}

template <typename T>
typename std::enable_if<!CreateProcessorImplemented<T>::value, void>::type Process(T value) {
    printf("Processor for requested typename is unavailable\n");
}


int main() {
    Process(42);
    Process("abc");

// static_assert(!CreateProcessorImplemented<char const*>::value, ":(");
/* This static_assert fails with an error:
 * code.cpp:56:5: error: static assertion failed: :(
 *      static_assert(!CreateProcessorImplemented<char const*>::value, ":(");
 */
}

虽然这会导致链接错误:

/tmp/ccTQRc9N.o:code.cpp:function std::enable_if<CreateProcessorImplemented<char const*, void>::value, void>::type Process<char const*>(char const*): error: undefined reference to 'IProcessor<char const*>* CreateProcessor<char const*>()'
collect2: error: ld returned 1 exit status

我的想法是,当我们解决 CreateProcessorImplemented<char const*> , decltype(CreateProcessor<const char*>())不会失败,因为有模板原型(prototype) IProcessor<T> CreateProcessor()并且编译器认为 decltype 等于 IProcessor<T>这在某种程度上是合乎逻辑的,但不是我需要的。

最佳答案

使其工作的一种方法是使用包装器结构来运行 CreateProcessor,如下所示:

#include <cstdio>
#include <type_traits>

// A workaround for void_t as described here: http://en.cppreference.com/w/cpp/types/void_t.
template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;

// An interface for a processor that receives a value of specific type.
template<class T>
class IProcessor {
public:
    virtual void process(T value) = 0;
};

// A processor for int.
class IntProcessor : public IProcessor<int> {
public:
    virtual void process(int value) override {
        printf("IntProcessor::process is called for value = %d\n", value);
    }
};

// Template prototype.
template<class T>
struct ProcessorCreator: std::false_type { 
   static IProcessor<T>* CreateProcessor();
};

// Template specialization for int.
template<>
struct ProcessorCreator<int>: std::true_type {
static IProcessor<int>* CreateProcessor() {
    return new IntProcessor();
}
};

// Detector of CreateProcessor.
template<class, class=void>
struct CreateProcessorImplemented : std::false_type { };

template<class T>
struct CreateProcessorImplemented<T, typename std::enable_if<ProcessorCreator<T>::value>::type > : std::true_type { };


// Specializations depending on existence of CreateProcessor.
template <typename T>
typename std::enable_if<CreateProcessorImplemented<T>::value, void>::type Process(T value) {
    IProcessor<T>* processor = ProcessorCreator<T>::CreateProcessor();
    processor->process(value);
}

template <typename T>
typename std::enable_if<!CreateProcessorImplemented<T>::value, void>::type Process(T value) {
    printf("Processor for requested typename is unavailable\n");
}


int main() {
    Process(42);
    Process("abc");

// static_assert(!CreateProcessorImplemented<char const*>::value, ":(");
/* This static_assert fails with an error:
 * code.cpp:56:5: error: static assertion failed: :(
 *      static_assert(!CreateProcessorImplemented<char const*>::value, ":(");
 */
}

或者,您可以删除模板声明并使用函数重载传递 IProcessor 模板参数类型——通过创建虚拟参数:

#include <cstdio>
#include <type_traits>

// A workaround for void_t as described here: http://en.cppreference.com/w/cpp/types/void_t.
template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;

// An interface for a processor that receives a value of specific type.
template<class T>
class IProcessor {
public:
    virtual void process(T value) = 0;
};

// A processor for int.
class IntProcessor : public IProcessor<int> {
public:
    virtual void process(int value) override {
        printf("IntProcessor::process is called for value = %d\n", value);
    }
};


IProcessor<int>* CreateProcessor(const int&) {
    return new IntProcessor();
}

// Detector of CreateProcessor.
template<class, class=void>
struct CreateProcessorImplemented : std::false_type { };

template<class T>
struct CreateProcessorImplemented<T, void_t<decltype(CreateProcessor(std::declval<T>()))>> : std::true_type { };


// Specializations depending on existence of CreateProcessor.
template <typename T>
typename std::enable_if<CreateProcessorImplemented<T>::value, void>::type Process(T value) {
    IProcessor<T>* processor = CreateProcessor(value);
    processor->process(value);
}

template <typename T>
typename std::enable_if<!CreateProcessorImplemented<T>::value, void>::type Process(T value) {
    printf("Processor for requested typename is unavailable\n");
}


int main() {
    Process(42);
    Process("abc");

// static_assert(!CreateProcessorImplemented<char const*>::value, ":(");
/* This static_assert fails with an error:
 * code.cpp:56:5: error: static assertion failed: :(
 *      static_assert(!CreateProcessorImplemented<char const*>::value, ":(");
 */
}

关于c++ - SFINAE 用于检测非成员模板函数的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35939855/

有关c++ - SFINAE 用于检测非成员模板函数的存在的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  4. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  5. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  6. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  7. Ruby Sinatra 配置用于生产和开发 - 2

    我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm

  8. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  9. ruby - inverse_of 是否适用于 has_many? - 2

    当我使用has_one时,它​​工作得很好,但在has_many上却不行。在这里您可以看到object_id不同,因为它运行了另一个SQL来再次获取它。ruby-1.9.2-p290:001>e=Employee.create(name:'rafael',active:false)ruby-1.9.2-p290:002>b=Badge.create(number:1,employee:e)ruby-1.9.2-p290:003>a=Address.create(street:"123MarketSt",city:"SanDiego",employee:e)ruby-1.9.2-p290

  10. ruby-on-rails - rspec - 如何检查方法是否存在? - 2

    我的模型有defself.empty_building//stuffend我怎样才能对这个现有的进行rspec?,已经尝试过:describe"empty_building"dosubject{Building.new}it{shouldrespond_to:empty_building}endbutgetting:Failure/Error:it{shouldrespond_to:empty_building}expected#torespondto:empty_building 最佳答案 你有一个类方法self.empty_bu

随机推荐