目前的签名是
\ntemplate<class TypeData,typename TypeFunc>\nbool isPrime(const TypeData& n,TypeFunc fSqrt,bool debug = false)\nRun Code Online (Sandbox Code Playgroud)\n这与
\nstd::cout<<(isPrime(n,fSqrt)?"Positive":"Negative")<<'\\n';\nRun Code Online (Sandbox Code Playgroud)\n但是,我的意图是这样的
\ntemplate<class TypeData,typename TypeFunc>\nbool isPrime(const TypeData& n,TypeFunc fSqrt = nullptr,bool debug = false)\nRun Code Online (Sandbox Code Playgroud)\n或者
\ntemplate<class TypeData,typename TypeFunc>\nbool isPrime(const TypeData& n,TypeFunc fSqrt = NULL,bool debug = false)\nRun Code Online (Sandbox Code Playgroud)\n被称为
\nstd::cout<<(isPrime(n)?"Positive":"Negative")<<'\\n';\nRun Code Online (Sandbox Code Playgroud)\n由于函数内部有静态变量,因此不可能重载。
\n只有不同才应该为此function-templateclass TypeData提供不同的template-functions。
请帮助我使用正确的语法。如果 C++ 不支持这一点,我可以使用什么替代方法?
\n编译错误
\n为了TypeFunc fSqrt = nullptr
main.cpp:90:23: error: …Run Code Online (Sandbox Code Playgroud) 如何防止浮点数在函数调用时隐式转换为整数值?
#include <iostream>
void fn(int x) {
std::cout<<"fn("<<x<<")\n";
}
int main() {
std::cout<<"Hello, this is 301014 :)\n";
fn(2);
fn(3.5);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里的输出分别是2和3。
我正在编译g++ -std=c++11 31014.cpp -o 31014 -v。并且没有提到3.5转换为3。
有没有办法防止或至少检测到这种情况?
请帮帮我。
fn(unique_ptr<A>{new A{}},unique_ptr<B>{new B{}});
Run Code Online (Sandbox Code Playgroud)
很麻烦,因为A如果B在那里抛出异常,就会发生泄漏。
fn(make_unique<A>(),make_unique<B>());
Run Code Online (Sandbox Code Playgroud)
另一方面被认为是异常安全的。
为什么?使用make_unique如何防止内存泄漏?make_unique做了
哪些默认的unique_ptr没有做的事情?
请帮帮我。
谢谢。
我应该如何修改我当前的函数签名
template<class TypeData,typename TypeFunc1 = Identity,typename TypeFunc2>
bool isPrime(const TypeData& n,TypeFunc1 calcSqrt = {},TypeFunc2 isDivisible = [](const TypeData& a,const TypeData& b) {return a%b==0;},const bool debug = false)
Run Code Online (Sandbox Code Playgroud)
为了被调用
auto fSqrt = [](decltype(n) v) {return std::sqrt(static_cast<float>(v));};
std::cout<<(isPrime(n,fSqrt)?"Positive":"Negative")<<'\n';
Run Code Online (Sandbox Code Playgroud)
Visual Studio 2019 提供
C2783 'bool isPrime(const TypeData &,TypeFunc1,TypeFunc2,const bool)':无法推导出 'TypeFunc2' 的模板参数
不过,没有 一切都很好TypeFunc2 isDivisible = [](const TypeData& a,const TypeData& b) {return a%b==0;}。
传递默认 lambda 的正确语法是什么?
请帮助我。
c++ ×4
c++11 ×1
c++17 ×1
function-templates-overloading ×1
g++ ×1
gcc ×1
lambda ×1
memory-leaks ×1
pointers ×1
templates ×1
unique-ptr ×1