我昨天问了一个关于模板方法重载和使用类型特征解决问题的问题。我收到了一些很好的答案,他们引导我找到了解决方案。这个解决方案让我进行了更多阅读。
我登陆了 Fluent CPP 的一个页面——https ://www.fluentcpp.com/2018/05/18/make-sfinae-pretty-2-hidden-beauty-sfinae/,这个页面很有趣,然后我听了博卡拉先生引用了斯蒂芬·杜赫斯特的讲话。这一切都令人着迷。
我现在正试图多了解一点。在昨天的答案中,我得到了这个解决方案:
template< class Function, class... Args,
std::enable_if_t<std::is_invocable_v<Function, Args...>, std::nullptr_t> = nullptr>
explicit MyClass( const std::string & theName, Function&& f, Args&&... args )
: name(theName)
{
runner(f, args...);
}
Run Code Online (Sandbox Code Playgroud)
在阅读了 CPP Fluent 帖子并观看了演讲之后,我得出了最终的解决方案:
template< class Function, class... Args>
using IsInvocable = std::enable_if_t < std::is_invocable_v<Function, Args...> >;
template< class Function, class... Args, typename = IsInvocable<Function, Args...> >
explicit ThreadHandle( const std::string & name, Function && f, Args &&... args ) {
startWithName(name, f, …
Run Code Online (Sandbox Code Playgroud) 这是我的代码和错误,下面我将展示一些有效的代码。
\n#include <iostream>\n#include <string>\n\n#include <nlohmann/json.hpp>\n\nusing JSON = nlohmann::json;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\ntemplate <class ObjectType>\nvoid dump(const JSON &json) {\n for (auto &[key, value]: json.items()) {\n string foo = value.get<std::string>();\n cout << "Key: " << key;\n cout << " Value: " << foo << endl;\n }\n}\n\nint main(int, char **) {\n JSON json;\n json["alpha"] = "beta";\n dump<string>(json);\n} \n
Run Code Online (Sandbox Code Playgroud)\n-$ g++ -std=c++17 Foo.cpp -o Foo && Foo\nFoo.cpp: In function \xe2\x80\x98void dump(const JSON&)\xe2\x80\x99:\nFoo.cpp:14:37: error: expected primary-expression before \xe2\x80\x98>\xe2\x80\x99 token\n 14 | string foo = …
Run Code Online (Sandbox Code Playgroud) 首先,我的代码:
#include <iostream>
#include <functional>
#include <string>
#include <thread>
#include <chrono>
using std::string;
using namespace std::chrono_literals;
class MyClass {
public:
MyClass() {}
// More specific constructor.
template< class Function, class... Args >
explicit MyClass( const std::string & theName, Function&& f, Args&&... args )
: name(theName)
{
runner(f, args...);
}
// Less specific constructor
template< class Function, class... Args >
explicit MyClass( Function&& f, Args&&... args ) {
runner(f, args...);
}
void noArgs() { std::cout << "noArgs()...\n"; }
void withArgs(std::string &) …
Run Code Online (Sandbox Code Playgroud)